package logic

import (
	"context"
	"encoding/json"
	"time"
	"zhihu/models/cache"
	"zhihu/models/mysql"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProblemTopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProblemTopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProblemTopListLogic {
	return &ProblemTopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProblemTopListLogic) ProblemTopList(in *zhihurpc.ProblemTopListRequest) (*zhihurpc.ProblemTopListResponse, error) {
	// todo: add your logic here and delete this line
	var problems []mysql.Problem

	get := cache.RedisDB.Get(l.ctx, "problemTopList")
	if get.Val() != "" {
		json.Unmarshal([]byte(get.Val()), &problems)
	} else {
		mysql.DB.Debug().Limit(10).Order("hot desc").Find(&problems)
		marshal, _ := json.Marshal(problems)
		cache.RedisDB.Set(l.ctx, "problemTopList", marshal, time.Minute*30)
	}
	var problemLists []*zhihurpc.ProblemTopList
	for _, problem := range problems {
		list := zhihurpc.ProblemTopList{
			ProblemImage: problem.ProblemImage,
			ProblemDesc:  problem.ProblemDesc,
			UserId:       int64(problem.UserId),
			Id:           int64(problem.ID),
			Hot:          int64(problem.Hot),
		}
		problemLists = append(problemLists, &list)
	}
	return &zhihurpc.ProblemTopListResponse{
		List: problemLists,
	}, nil
}
